package com.rchat.pocmini.activity.creategroup;

import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.airtalkee.sdk.AirtalkeeAccount;
import com.airtalkee.sdk.AirtalkeeChannel;
import com.airtalkee.sdk.OnChannelListener;
import com.airtalkee.sdk.entity.AirChannel;
import com.airtalkee.sdk.entity.AirContact;
import com.aso.common.http.bean.BaseBean;
import com.aso.common.http.delegate.HttpCallbackImpl;
import com.aso.common.utils.ToastUtils;
import com.rchat.pocmini.R;
import com.rchat.pocmini.account.PocAccount;
import com.rchat.pocmini.activity.fragment.groups.GroupsPresenterImpl;
import com.rchat.pocmini.activity.groupsselect.view.GroupSelectBean;
import com.rchat.pocmini.bean.AccountBean;
import com.rchat.pocmini.bean.CreateGroupBean;
import com.rchat.pocmini.bean2eventbus.EventBusAccountBean;
import com.rchat.pocmini.bean2eventbus.UpdateGroupBean;
import com.rchat.pocmini.channel.PocAirtalkeeChannel;
import com.rchat.pocmini.global.HttpCodeGlobal;
import com.rchat.pocmini.global.UrlsGlobal;
import com.rchat.pocmini.util.SPUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by ljd on 2017/7/28.
 * Modify by sudf on 2017/08/31
 */

public class CreateGroupPresenterImpl extends CreateGroupContract.Presenter implements OnChannelListener {
    /**
     * 普通会员可创建的最大群组数
     */
    public int GROUPSMAX = 5;
    private boolean isCreatting = false;
    /**
     * 标记当前是否可以执行后退
     * 使用场景：群组数大于5的VIP会员过期后，进入此页面尝试创建群组后，
     * 检测到已过期，用于又不选择保留的群组、不恢复VIP，则只能停留在该页面和退出应用
     */
    private boolean isCanBack = true;

    @Override
    void createGroup(String userName, String groupName) {
        if (isCreatting) {
            mView.showShortToast(R.string.is_creatting);
            return;
        }

        if (groupName.equals("")) {
            mView.showShortToast(R.string.group_name_null_error);
            return;
        }
        if (groupName.length() > 10) {
            mView.showShortToast(R.string.group_name_more_than_ten_error);
            return;
        }

        isCreatting = true;
        hideKeyboard();

        mModel.createGroup(userName, groupName, new HttpCallbackImpl<CreateGroupBean>() {
            @Override
            public void onStart() {
                mView.setProcessBarVisibility(View.VISIBLE);
            }

            @Override
            public void onSuccess(CreateGroupBean bean) {
                if (mView == null) {
                    return;
                }
                isCreatting = false;
                //调用频道界面刷新群组列表，此方式刷新后面还会修改
                UpdateGroupBean updateGroupBean = new UpdateGroupBean();
                updateGroupBean.setCurrentEvent(UpdateGroupBean.EVENT_GROPULIST_UPDATE);
                updateGroupBean.setTarget(this.getClass(), GroupsPresenterImpl.class, "onEventBusUpdateGroups");
                EventBus.getDefault().post(updateGroupBean);
                mView.showCreateGroupSuccessDialog();
                mView.updateVipGuide(1);
            }

            @Override
            public void onFailureResult(BaseBean bean) {
                if (mView == null) {
                    return;
                }
                isCreatting = false;
                if (bean.getCode().equals(HttpCodeGlobal.RES_CODE_440 + "")) {
                    onGroupsMax();
                } else {
                    mView.showNetError(bean.getCode(), bean.getDesc());
                }
            }

            @Override
            public void onFinish() {
                if (null == mView) {
                    return;
                }
                mView.setProcessBarVisibility(View.GONE);
            }
        });
    }

    /**
     * 获取账号信息
     *
     * @param bean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusRequestAccountStatus(EventBusAccountBean bean) {
        if (null == bean || !bean.isTarget(this.getClass())) {
            return;
        }
        switch (bean.getCurrentEvent()) {
            case EventBusAccountBean.EVENT_ACCOUNT_DATE:
                onRequestAccountStatus();
                break;
            default:
                break;
        }
    }

    /**
     * 请求账号信息：会员状态
     */
    private void onRequestAccountStatus() {
        mModel.requestAccountStatus(PocAccount.getUserId(), new HttpCallbackImpl<AccountBean>() {
            @Override
            public void onStart() {
                mView.showLoading();
            }

            @Override
            public void onSuccess(AccountBean bean) {
                if (mView == null) {
                    return;
                }
                ToastUtils.showToast(mActivity, "重启后可使用PTT键");
                PocAccount.setExpireDate(bean.getData().getExpireTime());
                if (bean.getData().getStatus() != (int) SPUtil.get(mActivity, SPUtil.SPKeyGlobal.KEY_VIP_STATUS, 0)) {
                    SPUtil.put(mActivity, SPUtil.SPKeyGlobal.KEY_VIP_STATUS, bean.getData().getStatus());
                }
                if (bean.getData().getStatus() == 2) {
                    isCanBack = true;
                    mView.updateVipGuide(1);
                }
            }

            @Override
            public void onFailureResult(BaseBean bean) {
                if (mView == null) {
                    return;
                }
//                mView.showNetError(bean.getDesc());
            }

            @Override
            public void onFinish() {
                if (null == mView) {
                    return;
                }
                mView.dismissLoading();
            }
        });
    }

    /**
     * 处理创建群组时发现群组数量已达上限
     */
    private void onGroupsMax() {
        PocAirtalkeeChannel.getPocAirtalkeeChannelInstance().setOnChannelListener(this);
        PocAirtalkeeChannel.getPocAirtalkeeChannelInstance().getChannelList(AirtalkeeChannel.CHANNEL_TYPE_SECRET);
    }

    @Override
    boolean isCanBack() {
        return isCanBack;
    }

    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onPStart() {
        super.onPStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onPDestroy() {
        EventBus.getDefault().unregister(this);
        super.onPDestroy();
    }

    @Override
    public void onChannelListGet(boolean b, List<AirChannel> list) {
        ArrayList<GroupSelectBean> data = new ArrayList<>();
        String userId = AirtalkeeAccount.getInstance().getUserId();
        for (AirChannel airChannel : list) {
            if (!airChannel.getCreatorId().equals(userId)) {
                continue;
            }
            GroupSelectBean bean = new GroupSelectBean();
            bean.setGroupName(airChannel.getDisplayName());
            bean.setGroupId(airChannel.getId());
            bean.setSelectStatus(false);
            data.add(bean);
        }
        if (data.size() <= GROUPSMAX) {
            isCanBack = true;
        } else {
            isCanBack = false;
        }
        mView.updateVipGuide(data.size());
    }

    @Override
    public void onChannelMemberListGet(String s, List<AirContact> list) {

    }

    @Override
    public void onChannelOnlineCount(LinkedHashMap<String, Integer> linkedHashMap) {

    }

    @Override
    public void onChannelPersonalCreateNotify(AirChannel airChannel) {

    }

    @Override
    public void onChannelPersonalDeleteNotify(AirChannel airChannel) {

    }

    @Override
    public void onChannelMemberAppendNotify(AirChannel airChannel, List<AirContact> list) {

    }

    @Override
    public void onChannelMemberDeleteNotify(AirChannel airChannel, List<AirContact> list) {

    }

    @Override
    public void onChannelMemberUpdateNotify(AirChannel airChannel, List<AirContact> list) {

    }

    @Override
    public void onChannelMemberUpdateNotify(AirChannel airChannel, AirContact airContact) {

    }
}
